package com.whf.web.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.whf.web.dto.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

/**
 * @PageableDefault用于对分页的pageable进行默认参数设置
 * 路径中的参数是可以使用正则表达式来规范参数格式的
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    //根据条件查询user,返回的user中仅仅显示username
    @GetMapping("/")
    //仅显示username
    @JsonView(User.SimpleUserView.class)
    public List<User> query(@PageableDefault(page = 1,size = 10) Pageable pageable){
        //TODO
        User user=new User();
        user.setUsername("张三");
        return Arrays.asList(user);
    }


    //根据id查询user,显示username和password
    @GetMapping("/{id:\\d+}")
    public User getInfo(@PathVariable(value = "id") String id){
        //TODO
        return null;
    }

    //添加user
    @PostMapping
    public User create(@Valid @RequestBody User user, BindingResult errors){
        //对传递进来的参数进行校验
        if(errors.hasErrors()){
            //TODO
        }
        //TODO
        return null;
    }

    //修改User
    @PutMapping("/{id}")
    public User update(@PathVariable String id,
                       @Valid @RequestBody User user,
                       BindingResult errors){
        //对传递进来的参数进行校验
        if(errors.hasErrors()){
            errors.getAllErrors().stream().forEach(error->{
                FieldError error1 = (FieldError) error;
                String err=error1.getField()+":"+error1.getDefaultMessage();
                log.error("[修改user] 传递参数有误:{}",err);
            });
            //TODO

        }
        //TODO
        return null;
    }

    //删除User
    @DeleteMapping("/{id}")
    public User delete(@PathVariable String id){
        //TODO
        return null;

    }



    @GetMapping("/get")
    public User get(){
        //TODO
        User user=new User();
        user.setUsername("张三");
        return user;
    }
}
